#include "GameFunctions.h"
#include "Entity.h"

bool WorldToScreen(VMatrix& W2SMatrix, SD_Tools::Vector2& ScreenSize, SD_Tools::Vector& World, SD_Tools::Vector2* Screen)
{
	Screen->x = W2SMatrix.x1 * World.x  +  W2SMatrix.x2 * World.y  +  W2SMatrix.x3 * World.z + W2SMatrix.x4;
	Screen->y = W2SMatrix.y1 * World.x  +  W2SMatrix.y2 * World.y  +  W2SMatrix.y3 * World.z + W2SMatrix.y4;
	float w = W2SMatrix.w1 * World.x  +  W2SMatrix.w2 * World.y  +  W2SMatrix.w3 * World.z + W2SMatrix.w4;
	if (w < 0.001f)
	{
		return false;
	}

	float invw = 1.0f / w;
	Screen->x *= invw;
	Screen->y *= invw;
	float x = ScreenSize.x / 2.0f;
	float y = ScreenSize.y / 2.0f;

	x += 0.5f * Screen->x * ScreenSize.x + 0.5f;
	y -= 0.5f * Screen->y * ScreenSize.y + 0.5f;

	Screen->x = x;
	Screen->y = y;

	return true;
}

bool IsVisible(SD_Tools::Vector& start, SD_Tools::Vector& end, Entity* pLocal, Entity* pEnemy)
{
	void* a;
	void* b;
	a = pLocal->GetBaseEntity();
	b = pEnemy->GetBaseEntity();
	if (!a || !b)
	{
		return false;
	}
	CTraceFilterSkipTwoEntities tracefilter(a, b);
	Ray_t Ray;
	trace_t trace;
	Ray.Init(start,end);
	g_pInterfaces.g_pEngineTrace->TraceRay(Ray,0x46004003,&tracefilter,&trace);
	if(trace.fraction > 0.97f)
	{
		return true;
	}
	return false;
}

SD_Tools::Angle CreateAimAngle(SD_Tools::Vector& Origin, SD_Tools::Vector& Target)
{
	SD_Tools::Vector Delta;
	SD_Tools::Angle AimAngle;

	Delta = SD_Tools::MathHelper::SubVector(Origin, Target);

	float Hyp = sqrt((Delta.x * Delta.x) + (Delta.y * Delta.y));

	AimAngle.x = SD_Tools::MathHelper::RadToDegf(atanf(Delta.z / Hyp));
	AimAngle.y = SD_Tools::MathHelper::RadToDegf(atanf(Delta.y / Delta.x));

	if(Delta.x >= 0.0f)
	{
		AimAngle.y += 180.0f;
	}
	AimAngle.z = 0.0f;

	return AimAngle;
}
